<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreBannerRequest;
use App\Http\Requests\UpdateBannerRequest;
use App\Http\Resources\ServiceResource;
use App\Models\Banner;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $sort = json_decode($request->sort, true);

        return Banner::query()
            ->when($title, function ($query) use ($title) {
                return $query->where('title', 'like', "%$title%");
            })
            ->when($sort, function ($query) use ($sort) {
                foreach ($sort as $item) {
                    $val = str_replace('end', '', $item['order']);
                    $query->orderBy($item['field'], $val);
                }
            }, function ($query) {
                return $query->orderBy('id', 'desc');
            })
            ->latest('orderby')
            ->get();
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreBannerRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreBannerRequest $request)
    {
        return $this->successful(Banner::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Banner  $banner
     * @return \Illuminate\Http\Response
     */
    public function show(Banner $banner)
    {
        return $this->successful($banner);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateBannerRequest  $request
     * @param  \App\Models\Banner  $banner
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateBannerRequest $request, Banner $banner)
    {
        return $this->successful($banner->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Banner  $banner
     * @return \Illuminate\Http\Response
     */
    public function destroy(Banner $banner)
    {
        return $this->successful($banner->delete());
    }

    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) return $this->failed('请选择要删除的记录');

        Banner::destroy($ids);
        return $this->successful('删除成功');
    }
}
